package com.rtx.config.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.rtx.edi.system.login.service.AuthUserServices;
import com.rtx.exception.RtxWmsException;
import com.rtx.model.emums.ExceptionCodeEnum;
import com.rtx.model.po.entity.system.User;

/**
 * XXX
 *
 * @author Zy
 */
public class UserRealm extends AuthorizingRealm {

    private static boolean licensed;

    private static long lastValidationTime;

    public static final long l = 1800000L;

    @Autowired
    private AuthUserServices authUserServices;

//    @Autowired
//    private RegisterServices registerServices;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        String username = userToken.getUsername();
        User user = authUserServices.queryUserByUsername(username);

//        if (!isLicensed()) {
//            throw new RtxWmsException(ExceptionCodeEnum.EXC_000009.getCode());
//        }

        if (user == null) {
            throw new RtxWmsException(ExceptionCodeEnum.EXC_000010.getCode());
        }

        if (0 == user.getLocked()) {
            throw new RtxWmsException(ExceptionCodeEnum.EXC_000011.getCode());
        }

        if (0 == user.getStatus()) {
            throw new RtxWmsException(ExceptionCodeEnum.EXC_000012.getCode());
        }

        ByteSource salt = ByteSource.Util.bytes(userToken.getUsername() + String.valueOf(userToken.getPassword()));
        return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), salt, getName());
    }

//    private boolean isLicensed() {
//
//        long currTimeMill = System.currentTimeMillis();
//        if (currTimeMill - lastValidationTime > l) {
//            try {
//                licensed = registerServices.isLicensed();
//                if (licensed) {
//                    lastValidationTime = currTimeMill;
//                }
//            } catch (Exception e) {
//                throw new RtxWmsException(e.getMessage());
//            }
//        }
//        return licensed;
//    }
//
//    public static boolean getLicensed() {
//        return licensed;
//    }
//
//    public static void setIsLicensed(boolean isLicensed) {
//        UserRealm.licensed = isLicensed;
//    }
}
